<?php

namespace App\Admin\Controllers\User;

use App\Admin\Actions\Extensions\userWithdrawalButton;
use App\Admin\Actions\Grid\User\UserWithdrawalProcessAction;
use App\Admin\Repositories\User\WxUserWithdrawal;
use App\Jobs\User\UserWithdrawalProcessJob;
use App\Jobs\User\UserWithdrawalQueryJob;
use App\Wen\Utils\Settings;
use App\Wen\Utils\Utils;
use Dcat\Admin\Form;
use Dcat\Admin\Grid;
use Dcat\Admin\Show;
use Dcat\Admin\Http\Controllers\AdminController;
use Dcat\Admin\Widgets\Metrics\Card;
use Illuminate\Support\Arr;

class WxUserWithdrawalController extends AdminController
{
    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        $mch_transfer_to_weChat = Settings::get('mch_transfer_to_weChat', 0) == 1;
        return Grid::make(new WxUserWithdrawal('user'), function (Grid $grid) use (&$mch_transfer_to_weChat) {
            $grid->simplePaginate();
            $grid->quickSearch(['id', 'withdrawal_id', 'user_id', 'user.user_name', 'wx_batch_id', 'ali_batch_id', 'bank_card', 'wechat_phone', 'alipay_phone'])->placeholder('搜索提现单号，用户id，用户名...')->width(35);
            $grid->model()->orderBy('id', 'desc');
            $grid->column('id')->sortable();
            $grid->column('withdrawal_id')->sortable()->display(function ($v){
                if(_empty_($v)){
                    \App\Models\User\WxUserWithdrawal::where('id', $this->id)->update([
                        'withdrawal_id' => Utils::getSn(14)
                    ]);
                }
                return $v;
            });
            $grid->column('owers', '头像')->display(function ($v) {
                return '<img src="' . ($this->ower['user_avatar'] ?? Settings::get('img_default', 'https://img.mini.minisns.cn/icons/dafault.png'))  . '"  style="border-radius:50px;width:30px;" />';
            })->width('50px');
            $grid->column('ower', '用户名称')->display(function ($v) {
                if($v && $v['user_name']){
                    return '<a target="_blank" href="'.admin_url('users?id='.$v['id']).'">'.$v['user_name'].'</a>' ?? '用户已删除';
                }
                return '用户已删除';
            })->width('100px');
            $grid->column('price');
            $grid->column('pay_amount');
            // 微信
            $grid->column('real_name');
            $grid->column('wechat_phone');
            $grid->column('alipay_phone');
            $grid->column('account_way')->display(function ($v){
                return _array_key(['wxpay'=>'微信零钱', 'alipay'=>'支付宝余额'], $v, '');
            });
            $grid->column('account_at');
            $grid->column('other','其他')->display('查看') // 设置按钮名称
            ->expand(function ($v) {

                $input['银行名字'] = $this->bank_name;
                $input['银行账号'] = $this->bank_card;
                $input['微信打款批次号'] = $this->wx_batch_id;
                $input['支付宝打款批次号'] = $this->ali_batch_id;
                $input['到账方式'] = _array_key(['wxpay'=>'微信零钱', 'alipay'=>'支付宝余额'], $this->account_way, '');
                $input['到账时间'] = $this->account_at;

                $str__ = '';
                foreach ($input as $key => $item){
                    if(!_empty_($str__)){
                        $str__ .= "\n";
                    }
                    $str__ .= $key . '：'. $item;
                }

                $input = $str__;
                // 只填充内容，不需要标题
                $card = Card::make(view('admin/system/log', compact('input')));
                return $card;
            });

            $grid->column('state')->using([0 => '待处理', 1 => '已处理', 2 => '异常', 3=>'微信打款中', 4=>'支付宝打款中', 5=>'尝试重新微信打款'])->label([
                0 => 'success',
                1 => 'pink',
                2 => 'primary',
                3 => '#29ad6a',
                4 => '#1578ff',
                5 => 'primary'
            ]);
            $grid->column('refuse_tip')->display(function ($v) use ($mch_transfer_to_weChat){
                if(_empty_($v)){
                    $v = '';
                }
                if($mch_transfer_to_weChat){
                    if($this->state === 0 && _empty_($this->wx_batch_id)){
                        UserWithdrawalProcessJob::dispatch($this->id);
                    }else if(!_empty_($this->wx_batch_id) && $this->state == 3){
                        UserWithdrawalQueryJob::dispatch($this->id);
                    }else if($this->state == 5 && _empty_($this->wx_batch_id)){
                        UserWithdrawalProcessJob::dispatch($this->id);
                    }
                }

                return $this->is_lock == 1 ? '🔒'.$v : $v;
            })->limit(20);
//            $grid->column('account_at');
            $grid->column('created_at')->sortable();

            $grid->filter(function (Grid\Filter $filter) {
                $filter->equal('id');
            });

            // 禁用新增按钮
            $grid->disableCreateButton();
            // 禁用编辑按钮
            $grid->disableEditButton();
            // 禁用详情按钮
//            $grid->disableViewButton();
            $grid->disableDeleteButton();
            $grid->disableBatchDelete();
            $grid->actions(function (Grid\Displayers\Actions $actions) {
                $actions->append((new UserWithdrawalProcessAction())->setKey($this->id));
            });

            $grid->tools([
//                new userWithdrawalButton(),
            ]);

        });
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     *
     * @return Show
     */
    protected function detail($id)
    {
        return Show::make($id, new WxUserWithdrawal(), function (Show $show) {
            $show->field('id');
            $show->field('withdrawal_id');
            $show->field('user_id');
            $show->field('price');
            $show->field('real_name');
            $show->field('id_card');

            $show->field('wechat_phone');
            $show->field('alipay_phone');

            $show->field('bank_name');
            $show->field('bank_card');
            $show->field('state');
            $show->field('refuse_tip');

            $show->field('account_at');
            $show->field('account_way');
            $show->field('account_way');
            $show->field('wx_batch_id');
            $show->field('ali_batch_id');

            $show->field('created_at');
            $show->field('updated_at');
            $show->field('is_lock');
            $show->disableEditButton();
            $show->disableDeleteButton();
        });
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        return Form::make(new WxUserWithdrawal(), function (Form $form) {
            $form->display('id');
            $form->text('user_id');
            $form->text('price');
            $form->text('state');
            $form->text('account_at');

            $form->deleting(function (Form $form){
                global $__MINI_GLOBAL_TENANT_ID__;
                if($__MINI_GLOBAL_TENANT_ID__ > 0){
                    return $form->response()->error('权限不足，不可以删除其他分站对象');
                }
            });

        });
    }
}
